<template>
  <div v-loading="loading" class="app-main-content-box">
    <!-- 标题 -->
    <app-main-title title="出价和库存管理" />
    <!-- 查询 -->

    <!-- filter start -->
    <div>
      <el-form ref="filterForm" :model="filterForm" label-width="100px" size="small">
        <div class="flexRSS">
          <div>
            <el-form-item label="管理模式：">
              <el-select v-model="filterForm.manageMode" placeholder="请选择">
                <el-option v-for="(item, key) in manageModeOptions" :key="key" :disabled="key === 'multiple' && userShopId !== 0" :label="item" :value="key" />
              </el-select>
            </el-form-item>
          </div>
          <div v-if="filterForm.manageMode === 'single'">
            <el-form-item label="管理门店：">
              <el-select v-model="filterForm.storeId" filterable placeholder="可通过名称搜索">
                <el-option v-for="(item, index) in shopOptions" :key="index" :label="item.name" :value="item.storeId" />
              </el-select>
            </el-form-item>
          </div>
        </div>
        <div class="flexRSS">
          <div>
            <el-form-item prop="title" label="商品名称：">
              <el-input v-model="filterForm.title" />
            </el-form-item>

            <el-form-item prop="barCode" label="国际条码：">
              <el-input v-model="filterForm.barCode" />
            </el-form-item>
          </div>
          <div>
            <el-form-item prop="categoryId" label="商品类目：">
              <el-cascader
                v-model="filterForm.categoryId"
                :options="categoryTreeOptions"
                :show-all-levels="false"
                :props="{
                  expandTrigger: 'hover',
                  checkStrictly: true,
                  label: 'title',
                  value: 'id',
                }"
                class="w-300"
              />
            </el-form-item>

            <el-form-item prop="goodsNo" label="商品编码：">
              <el-input v-model="filterForm.goodsNo" />
            </el-form-item>
          </div>
          <div>
            <el-form-item prop="goodsType" label="商品类型：">
              <el-select v-model="filterForm.goodsType" placeholder="请选择">
                <el-option label="全部" value="all" />
                <el-option v-for="(item, key) in goodsTypeOptions" :key="key" :label="item" :value="key" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="filterForm.manageMode === 'multiple'" prop="skuStatus" label="商品状态：">
              <el-select v-model="filterForm.skuStatus" placeholder="请选择">
                <el-option label="全部" value="all" />
                <el-option v-for="(item, key) in skuStatusOptions" :key="key" :label="item" :value="key" />
              </el-select>
            </el-form-item>
          </div>
        </div>

        <el-form-item>
          <el-button type="primary" round @click="search">查 询</el-button>
          <el-button round @click="reset">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- filter end -->

    <!-- table start -->

    <div class="table-container">
      <el-table :data="skuList" :span-method="arraySpanMethod" :cell-style="formatCellStyle" border stripe style="width: 100%" size="small" empty-text="暂无数据">
        <el-table-column prop="goods.title" label="商品">
          <template slot-scope="scope">
            <div class="goods-info-box flexRSC">
              <div class="cover-img">
                <img v-if="scope.row.goods.coverImg" :src="fileBaseUrl + scope.row.goods.coverImg" alt srcset>
              </div>
              <div>
                <div class="goods-title app-line-two">
                  {{ scope.row.goods.title }}
                </div>
                <div class="goods-detail app-line-two">
                  <span
                    v-if="
                      scope.row.goods.categoryId === 0 ||
                        scope.row.goods.category.length === 0
                    "
                  >无归属类目</span>
                  <span v-else>
                    <span v-for="(attr, attrIndex) in scope.row.goods.category" :key="attrIndex">
                      {{ attr }}
                      <span v-if="attrIndex + 1 !== scope.row.goods.category.length">/</span>
                    </span>
                  </span>
                </div>
                <div class="goods-detail app-line-two">
                  {{ goodsTypeOptions[scope.row.goods.goodsType] }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="skuList" label="属性">
          <template slot-scope="scope">
            <span v-if="scope.row.skuInfo.specAttrNameList.length === 0">/</span>
            <span v-else>
              <span v-for="(attr, attrIndex) in scope.row.skuInfo.specAttrNameList" :key="attrIndex">
                {{ attr }}
                <span
                  v-if="
                    attrIndex + 1 !== scope.row.skuInfo.specAttrNameList.length
                  "
                >/</span>
              </span>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="skuList.skuInfo.originPrice" label="市场价/元" width="110">
          <template slot-scope="scope">{{
            scope.row.skuInfo.originPrice / 100
          }}</template>
        </el-table-column>
        <el-table-column prop="skuList.skuInfo.price" label="参考售价/元" width="110">
          <template slot-scope="scope">{{
            scope.row.skuInfo.price / 100
          }}</template>
        </el-table-column>

        <!-- 多店铺  -->
        <div v-if="filterForm.manageMode === 'multiple'">
          <el-table-column prop="skuList.storeCount" label="出价店铺" width="110">
            <template slot-scope="scope">{{ scope.row.storeCount }} 家门店</template>
          </el-table-column>
          <el-table-column prop="skuList.skuInfo.status" label="状态" width="110">
            <template slot-scope="scope">
              <div
                :class="
                  scope.row.skuInfo.status
                    ? 'app-text-color-primary'
                    : 'app-text-color-danger'
                "
              >
                {{ skuStatusOptions[scope.row.skuInfo.status] }}
              </div>
            </template>
          </el-table-column>
        </div>
        <!-- 单店铺  -->
        <div v-if="filterForm.manageMode === 'single'">
          <el-table-column prop="skuList.skuInfo.price" label="店铺售价/元" width="110">
            <template slot-scope="scope">{{
              scope.row.storePrice == -1
                ? scope.row.skuInfo.originPrice / 100
                : scope.row.storePrice / 100
            }}</template>
          </el-table-column>

          <el-table-column prop="storeStatus" label="店铺在售" width="110">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.storeStatus" :active-value="1" :nactive-value="0" @change="(val) => changeSingleState(val, scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="skuList.skuInfo.price" label="库存" width="110">
            <template slot-scope="scope">{{
              scope.row.storeInventory
            }}</template>
          </el-table-column>
        </div>

        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="openDialogEditSku(scope.row)">出价</el-button>
            <el-button
              v-if="filterForm.manageMode === 'multiple'"
              :class="
                scope.row.skuInfo.status
                  ? 'app-text-color-danger'
                  : 'app-text-color-primary'
              "
              type="text"
              size="small"
              @click="changeSingleStatus(scope.row)"
            >{{ scope.row.skuInfo.status ? "下架" : "上架" }}</el-button>
            <el-button v-if="scope.row.storeCount" type="text" size="small" @click="openDialogShareSku(scope.row)">分享</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination-direction v-if="paginationConfig.total !== 0" :config="paginationConfig" @sizeschange="sizesChange" @pagechange="pageChange" />
    </div>
    <!-- table end -->

    <!-- 组件 -->
    <DialogEditSku ref="dialogEditSku" />
    <DialogShareSku ref="dialogShareSku" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { productList } from '@/views/wxaMallModule/api/product'
import { categoryTree } from '@/views/wxaMallModule/api/category'
import {
  productSkuListByShop,
  productSkuList,
  modifyProductSkuStatus,
  modifyProductSkuState
} from '@/views/wxaMallModule/api/sku'
import { mapActions } from 'vuex'
import { storeList } from '@/views/wxaMallModule/api/shop'
import DialogEditSku from './components/DialogEditSku'
import DialogShareSku from './components/DialogShareSku'
export default {
  components: {
    DialogEditSku,
    DialogShareSku
  },
  data() {
    return {
      // 配置
      manageModeOptions: {
        single: '单店铺管理模式',
        multiple: '多店铺管理模式'
      },
      goodsTypeOptions: {
        100: '实物商品',
        200: '卡/券包'
        // 300: "同城配送",
      },
      skuStatusOptions: {
        0: '已下架',
        1: '已上架'
      },
      categoryTreeOptions: [],
      shopOptions: [],
      shopKeyOptions: {},
      shopOptionsLoaded: false,
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      // 状态
      loading: false,
      // 数据
      filterForm: {
        manageMode: '',
        goodsType: 'all',
        barCode: '',
        brandId: '',
        categoryId: [0],
        goodsNo: '',
        skuStatus: 'all',
        title: '',
        storeId: ''
      },
      list: [],
      skuList: [],
      skuRowSpan: {}
    }
  },
  watch: {
    'filterForm.manageMode'(newVal, oldValue) {
      if (oldValue !== '' && newVal) {
        this.fetchData()
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl', 'userShopId'])
  },
  created() {},
  mounted() {
    if (this.userShopId !== 0) {
      this.filterForm.manageMode = 'single'
    } else {
      this.filterForm.manageMode = 'multiple'
    }
    this.fetchData()
    this.getCategoryOptions()
    this.getActiveMaIsOnline()
  },
  methods: {
    /**
       * 数据组
       */
    // 获取小程序是否上线
    ...mapActions(['getAuthMa']),
    getActiveMaIsOnline() {
      this.getAuthMa()
    },

    // 获取列表
    async fetchData(
      pageNum = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      if (!this.shopOptionsLoaded) await this.getShopOptions()
      this.loading = true
      // 加入page
      this.filterForm.pageNum = pageNum
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      if (
        params.categoryId.length === 0 ||
          (params.categoryId.length === 1 && params.categoryId[0] === 0)
      ) {
        params.categoryId = ''
      } else {
        params.categoryId = params.categoryId[params.categoryId.length - 1]
      }
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      this.loading = true

      /* 单门店模式 */
      if (params.manageMode === 'single') {
        delete params.skuStatus
        if (!params.storeId) {
          this.filterForm.storeId = params.storeId = this.shopOptions[0].storeId
          //  = this.shopOptions[0].storeId;
        }
        productSkuListByShop(params)
          .then((res) => {
            this.formatSkuList(res)
          })
          .finally(() => {
            this.loading = false
          })
      }

      /* 多门店模式 */
      if (params.manageMode === 'multiple') {
        delete params['storeId']
        productSkuList(params)
          .then((res) => {
            this.formatSkuList(res)
          })
          .finally(() => {
            this.loading = false
          })
      }
    },

    // 格式化列表
    formatSkuList(res) {
      const skuList = []
      const skuRowSpan = {}
      res.data.list.forEach((item) => {
        skuRowSpan[item.goods.goodsId] = [0, 0]
        item.skuList.forEach((skuItem, skuIndex) => {
          if (skuIndex === 0) {
            skuRowSpan[item.goods.goodsId][0] = skuList.length
            skuRowSpan[item.goods.goodsId][1] = item.skuList.length
          }
          skuItem.goods = item.goods
          skuList.push(skuItem)
        })
      })
      this.skuRowSpan = skuRowSpan
      this.skuList = skuList
      this.list = res.data.list
      this.paginationConfig.total = res.data.total
      this.paginationConfig.page = res.data.pageNum
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    // 获取类目tree
    getCategoryOptions() {
      return new Promise((resolve, reject) => {
        categoryTree()
          .then((res) => {
            this.categoryTreeOptions = [
              {
                categoryNo: '',
                children: undefined,
                id: 0,
                parentId: 0,
                ranking: 0,
                title: '全部'
              }
            ].concat(this.formatTreeData(res.data))
          })
          .catch((err) => {})
          .finally(() => {})
      })
    },

    // 递归children设置空
    formatTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.formatTreeData(data[i].children)
        }
      }
      return data
    },

    // 获取门店列表
    getShopOptions() {
      return new Promise((resolve, reject) => {
        storeList()
          .then((res) => {
            this.shopOptionsLoaded = true
            let shopList = []
            const shopKey = {}
            res.data.some((v) => {
              shopKey[v.storeId] = v.name
              if (v.shopId === this.userShopId) {
                shopList = [v]
                return true
              } else {
                shopList.push(v)
              }
            })
            this.shopOptions = shopList
            this.shopKeyOptions = shopKey
            if (shopList.length === 0) {
              this.$alert('未入驻店铺，请先入驻店铺', '温馨提示', {
                confirmButtonText: '确定',
                type: 'warning',
                center: true,
                roundButton: true,
                callback: (action) => {
                  this.$router.push({ name: 'WxaMallShopManage' })
                }
              })
            } else {
              resolve()
            }
          })
          .catch((err) => {})
          .finally(() => {})
      })
    },

    // 上下架
    modifyStatus(params) {
      this.loading = true
      modifyProductSkuStatus(params)
        .then((res) => {
          this.fetchData()
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false
        })
    },

    // 编辑价格&状态
    modifyState(params) {
      this.loading = true
      modifyProductSkuState(params)
        .then((res) => {
          this.getSkuInfo()
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false
        })
    },

    /**
       * 按钮组
       */
    // 弹框价格
    openDialogEditSku(row) {
      let storeId = ''
      let storeName = ''
      if (this.filterForm.manageMode === 'single') {
        storeId = this.filterForm.storeId
        storeName = this.shopKeyOptions[storeId]
      }
      this.$refs.dialogEditSku.open({ row, storeId, storeName }).then((res) => {
        this.fetchData()
      })
    },

    // 打开分享
    openDialogShareSku(row) {
      if (!this.$store.state.wechat.maInfo.DEFAULT.isOnline) {
        this.$alert('商户小程序未正式发布，暂时不可以获取二维码！', '提示', {
          confirmButtonText: '确定',
          center: true,
          type: 'warning',
          roundButton: true,
          callback: (action) => {}
        })
      } else {
        let shopOptions = []
        if (this.filterForm.manageMode === 'single') {
          shopOptions = [
            {
              storeId: this.filterForm.storeId,
              name: this.shopKeyOptions[this.filterForm.storeId]
            }
          ]
        } else {
          shopOptions = this.shopOptions
        }
        this.$refs.dialogShareSku.open({ row, shopOptions }).then((res) => {})
      }
    },

    // 修改上下架单个
    changeSingleStatus(row) {
      const params = {
        skuIdList: [row.skuInfo.skuId],
        status: row.skuInfo.status ? 0 : 1
      }
      this.modifyStatus(params)
    },

    // 修改状态单个
    changeSingleState(value, row) {
      const params = {
        skuId: row.skuInfo.skuId,
        status: value ? 1 : 0,
        storeIdList: [this.filterForm.storeId]
      }
      this.modifyState(params)
    },

    // 查询
    search() {
      this.fetchData(1)
    },

    // 重置
    reset() {
      this.$refs.filterForm.resetFields()
    },

    /**
       * 状态组
       */

    /**
       * 方法组
       */
    // 合并单元格
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const spanArr = this.skuRowSpan[row.goods.goodsId]
        if (rowIndex === spanArr[0]) {
          return [spanArr[1], 1]
        } else {
          return [0, 0]
        }

        // return this.skuRowSpan[row.goods.goodsId];
      }
      // if (rowIndex % 2 === 0) {
      //   if (columnIndex === 0) {
      //     return [1, 2];
      //   } else if (columnIndex === 1) {
      //     return [0, 0];
      //   }
      // }
    },

    // 增长率样式
    formatCellStyle({ row, column, rowIndex, columnIndex }) {
      switch (columnIndex) {
        case 0:
          return {
            'vertical-align': 'top'
            // display: "block",
            // height: "100%",
            // display: "flex",
            // flexDirection: "column",
          }
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .el-dropdown-link {
    margin-right: 10px;
    font-size: 12px;
  }
  .el-select,
  .el-input,
  .el-cascader {
    width: 250px;
  }
  /* 商品内容 */
  .goods-info-box {
    .cover-img {
      margin-right: 10px;
      flex: 0 0 50px;
      height: 50px;
      border: 1px solid #e7e7e7;
    }
    .goods-title {
      font-size: 14px;
      font-weight: bold;
      color: #000;
    }
    .goods-detail {
      font-size: 12px;
    }
  }
</style>
